package com.netclass.meethealth.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.netclass.meethealth.R;
import com.netclass.meethealth.adapter.PartApplyAdapter;
import com.netclass.meethealth.callback.ApplyCallBack;
import com.netclass.meethealth.callback.BoolCallBack;
import com.netclass.meethealth.model.Apply;
import com.netclass.meethealth.model.Sport;
import com.netclass.meethealth.srv.SportService;
import com.netclass.meethealth.srv.impl.SportSrvImpl;
import com.netclass.meethealth.tools.PreferenceManager;

import java.util.ArrayList;
import java.util.List;

/**
 * 组团运动详情
 *
 * @author luodong
 * @TODO :
 * 如果本人是发起人：显示所有信息（包括每个人的手机号和姓名）
 * 如果本人是参与者：显示自己的信息和报名人数
 * 如果本人是游客：显示报名人数
 */
public class PartDetailActivity extends Activity {

    //服务
    private SportService sportService;

    //简介
    private TextView tvTitle;
    //活动地点距离
    private TextView tvDistance;
    //申请报名
    private ImageView ivApply;
    //申请退出
    private ImageView ivCancel;
    //发布用户名称
    private TextView tvUserName;
    //发布用户距离
    private TextView tvUserDistance;
    //剩余时间
    private TextView tvLeftTime;
    //剩余时间单位
    private TextView tvLeftTimePer;
    //报名人数
    private TextView tvApplyNum;
    //报名信息
    private ListView applyListView;

    //组团信息
    private Sport sport;
    //适配器
    private PartApplyAdapter partApplyAdapter;

    //权限类型 -1:游客;0:参与者;1:发起者
    private int myAuth = -1;

    //我的信息
    private String mPhone;
    private String mName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_part_detail);

        sportService = new SportSrvImpl();
        sport = (Sport) getIntent().getExtras().get("sport");

        mName = PreferenceManager.getString(this, "name");
        mPhone = PreferenceManager.getString(this, "phone");

        initView();
        initListeners();

        loadData();
    }

    /**
     * 加载网络数据
     */
    private void loadData() {
        sportService.viewApplys(sport.getId(), mPhone, new ApplyCallBack() {
                    @Override
                    public void onSuccess(final Apply sport) {
                        //说明已加入了
                        myAuth = 0;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ivCancel.setEnabled(true);
                                ivApply.setEnabled(false);

                                List<Apply> applies = new ArrayList<Apply>();
                                applies.add(sport);

                                if (partApplyAdapter == null) {
                                    partApplyAdapter = new PartApplyAdapter(PartDetailActivity.this, applies);
                                    applyListView.setAdapter(partApplyAdapter);
                                } else {
                                    partApplyAdapter.refresh(applies);
                                }
                            }
                        });
                    }

                    @Override
                    public void onGetList(final List<Apply> applyList) {
                        //说明是发起者
                        myAuth = 0;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ivApply.setEnabled(false);
                                ivCancel.setEnabled(false);
                                if (partApplyAdapter == null) {
                                    partApplyAdapter = new PartApplyAdapter(PartDetailActivity.this, applyList);
                                    applyListView.setAdapter(partApplyAdapter);
                                } else {
                                    partApplyAdapter.refresh(applyList);
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailed(String message) {
                        //失败

                    }

                    @Override
                    public void onNull() {
                        //说明是游客
                        myAuth = -1;
                        runOnUiThread(new Runnable() {
                                          @Override
                                          public void run() {
                                              ivApply.setEnabled(true);
                                              ivCancel.setEnabled(false);
                                              if (partApplyAdapter != null) {
                                                  partApplyAdapter.refresh(new ArrayList<Apply>());
                                              }
                                          }
                                      }

                        );
                    }
                }

        );

    }

    /**
     * 初始化监听
     */

    private void initListeners() {
//        点击申请
        ivApply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sportService.applySport(sport.getId(), mName, mPhone, new BoolCallBack() {
                    @Override
                    public void onYes() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PartDetailActivity.this, "报名成功!", Toast.LENGTH_SHORT).show();
                                ivApply.setEnabled(false);
                                ivCancel.setEnabled(true);
                                loadData();
                            }
                        });
                    }

                    @Override
                    public void onNo() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PartDetailActivity.this, "报名失败!", Toast.LENGTH_SHORT).show();
                                ivApply.setEnabled(false);
                                ivCancel.setEnabled(true);
                            }
                        });
                    }
                });
            }
        });

//        点击退出
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sportService.deleteApply(sport.getId(), mPhone, new BoolCallBack() {
                    @Override
                    public void onYes() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PartDetailActivity.this, "退出成功!", Toast.LENGTH_SHORT).show();
                                ivApply.setEnabled(true);
                                ivCancel.setEnabled(false);
                                loadData();
                            }
                        });
                    }

                    @Override
                    public void onNo() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PartDetailActivity.this, "退出失败!", Toast.LENGTH_SHORT).show();
                                ivApply.setEnabled(false);
                                ivCancel.setEnabled(true);

                            }
                        });
                    }
                });
            }
        });
    }

    /**
     * 初始化视图
     */
    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvDistance = (TextView) findViewById(R.id.tv_distance);
        ivApply = (ImageView) findViewById(R.id.iv_apply);
        ivCancel = (ImageView) findViewById(R.id.iv_cancel);
        tvUserName = (TextView) findViewById(R.id.tv_user_name);
        tvUserDistance = (TextView) findViewById(R.id.tv_user_distance);
        tvLeftTime = (TextView) findViewById(R.id.tv_title);
        tvLeftTimePer = (TextView) findViewById(R.id.tv_left_time_type);
        tvApplyNum = (TextView) findViewById(R.id.tv_apply_num);
        applyListView = (ListView) findViewById(R.id.lv_applys);


        tvTitle.setText(sport.getIntro());
        tvDistance.setText(sport.getPla_distance() / 1000.00 + "");
        tvApplyNum.setText(sport.getApply_num() + "");
        CharSequence charSequence = getResources().getString(R.string.user_name, sport.getName(), sport.getUser_distance() > 1000 ? "km" : "m");
        tvUserName.setText(charSequence);
        CharSequence charSequence1 = getResources().getString(R.string.left_time, sport.getDelay() > 60 ? (sport.getDelay() > 60 * 60 ? "小时" : "分钟") : "秒");
        tvLeftTimePer.setText(charSequence1);
        tvLeftTime.setText((sport.getDelay() > 60 ? (sport.getDelay() > 60 * 60 ? sport.getDelay() / 3600 : sport.getDelay() / 60) : sport.getDelay()) + "");
        tvUserDistance.setText((sport.getUser_distance() > 1000 ? sport.getUser_distance() / 1000 : sport.getUser_distance()) + "");

        ivApply.setEnabled(false);
        ivCancel.setEnabled(false);
    }

}
